package com.witframework.web.tree;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @author wuxinyang
 * May 13, 2009 11:53:41 AM
 *
 */
public class TreeNode {

	private TreeItem rootNode=null;
	private List<TreeItem> treeItems=new ArrayList<TreeItem>();


	public TreeNode(){
	}
	public void addItem(TreeItem item){
		treeItems.add(item);
	}

	public void setRootNode(TreeItem rootNode){
		this.rootNode=rootNode;
	}
	public String outString(){
		StringBuffer treeXml=new StringBuffer("");//<?xml version=\"1.0\" encoding=\"UTF-8\"?>
		if(rootNode!=null){
			treeXml.append("<tree id=\""+rootNode.getId()+"\" ");
			treeXml.append(">");
		}
		treeItems.addAll(rootNode.getChildItems());
		for(int i=0;i<treeItems.size();i++){
			TreeItem item=treeItems.get(i);
			treeXml.append(outItem(item));
		}
		if(rootNode!=null)
			treeXml.append("</tree>");
		return treeXml.toString();
	}
	private String outItem(TreeItem item){
		StringBuffer treeXml=new StringBuffer();
		treeXml.append("<item id=\""+clearXmlText(item.getId()));
		treeXml.append("\" text=\""+clearXmlText(item.getText())+"\"");
		treeXml.append(" child=\""+item.getChild()+"\"");
		if(item.getTooltip()!=null&&item.getTooltip().length()>0)
			treeXml.append(" tooltip=\""+item.getTooltip()+"\" ");		;
		if(item.isCheckbox())
			treeXml.append(" checkbox=\"1\"");
		else
			treeXml.append(" nocheckbox=\"1\"");
		if(item.isSelect())
			treeXml.append(" select=\"1\"");
		if(item.isOpen())
			treeXml.append(" open=\"1\"");
		if(item.isCall())
			treeXml.append(" call=\"1\"");
		if(item.getImg0()!=null){
			treeXml.append(" im0=\""+item.getImg0()+"\"");			
		}
		if(item.getImg1()!=null){
			treeXml.append(" im1=\""+item.getImg1()+"\"");			
		}
		if(item.getImg2()!=null){
			treeXml.append(" im2=\""+item.getImg2()+"\"");			
		}
		treeXml.append(">");
		if(item.getChildItems().size()!=0){
			for(int i=0;i<item.getChildItems().size();i++){
				treeXml.append(outItem(item.getChildItems().get(i)));
			}
		}
		for(int i=0;i<item.getTreeUserdatas().size();i++){
			TreeUserdata userdata=item.getTreeUserdatas().get(i);
			treeXml.append(outUserdata(userdata));
		}
		treeXml.append("</item>");
		return treeXml.toString();
	}
	private String outUserdata(TreeUserdata userdata){
		StringBuffer treeXml=new StringBuffer();
		treeXml.append("<userdata name=\""+userdata.getName()+"\"><![CDATA[");
		treeXml.append(userdata.getData());
		treeXml.append("]]></userdata>");
		return treeXml.toString();
	}
	//valid ones are  \b  \t  \n  \f  \r  \"  \'  \\
	private String clearXmlText(String text){
		if(text==null) return "";
		text=text.replace("'","");
		text=text.replace(">","");
		text=text.replace("<","");
		return text;
	}
}
